package com.huasan.www.demon.rest.resource;

import java.util.List;
import java.util.UUID;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.huasan.www.demon.data.service.UserinfoService;
import com.huasan.www.demon.pojo.Userinfo;
import com.huasan.www.demon.pojo.UserinfoExample;

@Path("/login")
public class LoginResource {

	@Autowired
	private UserinfoService userinfoService;
	
	private Logger logger = LoggerFactory.getLogger(LoginResource.class);
	
	public static final String JSON_TEMPLATE = "{\"status\":\"{0}\",\"data\":\"{1}\", \"userid\":\"{2}\", \"msg\":\"{3}\"}";
	
	@POST
	@Produces({MediaType.APPLICATION_JSON} )
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String mGetLogin(@FormParam("username") String loginname, @FormParam("password") String password){
		try{
			UserinfoExample example = new UserinfoExample();
			UserinfoExample.Criteria criteria = example.createCriteria();
			criteria.andLoginnameEqualTo(loginname);
			criteria.andPwdEqualTo(password);
			List<Userinfo> list = userinfoService.selectByExample(example);
			if (list.size()==0)
				return this.getErrRet("用户名或密码错误");
			
			Userinfo userinfo = list.get(0);
			if (userinfo.getSid()==null){
				userinfo.setSid(UUID.randomUUID().toString());
				userinfoService.updateByPrimaryKey(userinfo);
			}
			System.out.println(userinfo.getSid());
			return getOkRet( userinfo.getSid() , userinfo.getId().toString(), "");
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return this.getErrRet("查询失败");
		}
	}
	
	@POST
	@Path("/register")
	@Produces({MediaType.APPLICATION_JSON} )
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String mGetRegiste(@FormParam("username") String loginname, @FormParam("password") String password,
				@FormParam("mobile") String mobile, @FormParam("nickname") String nickname, 
				@FormParam("mail") String mail, @FormParam("optname") String optname,
				@FormParam("locale") String locale){
		try{
			if (loginname == null || password == null || "".equals(loginname) || "".equals(password))
				return this.getErrRet("用户名或密码为空");
			UserinfoExample example = new UserinfoExample();
			UserinfoExample.Criteria criteria = example.createCriteria();
			criteria.andLoginnameEqualTo(loginname);
			List<Userinfo> list = userinfoService.selectByExample(example);
			if (list.size()>0)
				return this.getErrRet("用户名或密码已存在");
			
			Userinfo userinfo = new Userinfo();
			userinfo.setLoginname(loginname);
			userinfo.setPwd(password);
			userinfo.setSid( UUID.randomUUID().toString() );
			userinfo.setMail(mail);
			userinfo.setMobileno(mobile);
			userinfo.setLocale(locale);
			userinfo.setOptname(optname);
			userinfo.setNickname(nickname);
			userinfoService.insertSelective(userinfo);
			return getOkRet( userinfo.getSid() , userinfo.getId().toString(), "");
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return this.getErrRet("创建用户失败");
		}
	}
	
	@POST
	@Path("/checkname")
	@Produces({MediaType.APPLICATION_JSON} )
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public String mGetCheckName(@FormParam("username") String loginname){
		try{
			if (loginname == null || "".equals(loginname))
				return this.getErrRet("用户名为空");
			UserinfoExample example = new UserinfoExample();
			UserinfoExample.Criteria criteria = example.createCriteria();
			criteria.andLoginnameEqualTo(loginname);
			List<Userinfo> list = userinfoService.selectByExample(example);
			if (list.size()>0)
				return this.getErrRet("用户名已存在");
			else
				return this.getOkRet("","","用户名可以使用");
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return this.getErrRet("检查用户失败");
		}
	}
	
	private String getOkRet(String sid, String uid, String msg){
		return JSON_TEMPLATE.replace("{0}", "ok").replace("{1}", sid)
				.replace("{2}", uid).replace("{3}", msg);
	}
	
	private String getErrRet( String msg ){
		return JSON_TEMPLATE.replace("{0}", "err").replace("{1}", "")
				.replace("{2}", "").replace("{3}", msg);
	}
}
